package com.rocksea.app.http;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.util.Log;

import com.mor.dataacquisition.net.BaseParser;
import com.mor.dataacquisition.net.RequestValue;
import com.mor.dataacquisition.util.DataCheck;
import com.mor.dataacquisition.util.MyLog;
import com.rocksea.app.Account;
import com.rocksea.app.MyApplication;
import com.rocksea.app.db.DbCenter;
import com.rocksea.app.db.image.ImageTable;
import com.rocksea.app.utils.HttpMessage;

import org.restlet.data.Form;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;

public class UploadImageThread extends Thread
{
    private static boolean working = true;

    private String planNum;
    private String pileNo;

    private UploadImageThread()
    {
        super("UploadImageThread");
    }

    public UploadImageThread(String planNum, String pileNo)
    {
        this();
        working = true;
        this.pileNo = pileNo;
        this.planNum = planNum;
    }

    @Override
    public void run()
    {
        ArrayList<ImageTable> imageTables = DbCenter.mImageDbHelper.query(planNum,pileNo);
        if (imageTables != null && imageTables.size() > 0)
        {
            int position = 0;
            for (ImageTable imageTable : imageTables)
            {
                position++;
                if (imageTable.getUpLoadTime() > 0)
                    continue;
                HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,String.format("正在上传图片(%s/%s)",position,imageTables.size()));
                int type = imageTable.getIsSonicWave() == 0 ? 0 : 1;
                File file = new File(imageTable.getFilePath());
                int checkCode = DataCheck.uploadImage(Account.getRandomCode(),
                        Account.getAccount(),
                        file,
                        imageTable.getPileId(),
                        imageTable.getPlanNum(),
                        imageTable.getPileNo(),
                        type,
                        imageTable.getCreatTime(),
                        imageTable.getRemake());
                if (checkCode != 0)
                {
                    HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,String.format("上传图片异常(%s),请手动上传", HttpMessage.getErrorInfo(HttpMessage.uploadImage,checkCode)));
                    break;
                }
                RequestValue rValue = new RequestValue();
                rValue.context = MyApplication.getContext();
                rValue.url = Config.BASE_URL+Config.uploadImage;
                MyLog.i("sendapi_demo", "rValue.url: " + rValue.url);
                rValue.parser = new BaseParser();
                String path = file.getAbsolutePath();
                String img_name = file.getName();
                Bitmap bitmap = BitmapFactory.decodeFile(path);
                String file_content = bitmap2String(bitmap);
                bitmap.recycle();

                while (working && isAlive())
                {
                    Form form = new Form();
                    form.add("randomCode", Account.getRandomCode());
                    form.add("account", Account.getAccount());
                    form.add("inspectionFormId", String.valueOf(imageTable.getPileId()));
                    form.add("inspectionFormNum", imageTable.getPlanNum());
                    form.add("pileNo", imageTable.getPileNo());
                    form.add("testType", String.valueOf(imageTable.getType()));
                    form.add("eventTime", imageTable.getCreatTime());
                    form.add("eventInfo", imageTable.getRemake());
                    form.add("fileType", String.valueOf(type));
                    form.add("sectionId", imageTable.getSectionId());
                    form.add("file_content", file_content);
                    form.add("img_name", img_name);
                    rValue.form = form;
                    int code = HttpUtil.doNetRest(rValue,rValue.form);
                    if (code == 0 || code == -98)
                    {
                        DbCenter.makeImageAsUpLoad(imageTable.getPileId(),imageTable.getFileName());
                        break;
                    }
                    else if (code == -1)
                    {
                        Account.setRandomCode(HttpUtil.upDateRandomCode());
                    }
                    else
                    {
                        HttpUtil.postEvent(HttpUtil.UploadEvent.ERROR,String.format("上传异常(%s)",HttpMessage.getErrorInfo(HttpMessage.uploadImage,code)));
                        Log.e("UploadImageThread", code+"" );
                        try
                        {
                            sleep(1000);
                        }
                        catch (InterruptedException e)
                        {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        HttpUtil.postEvent(HttpUtil.UploadEvent.NORMAL,"上传完成");
    }

    private static String bitmap2String(Bitmap bitmap)
    {
        String string;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, 0);
        return string;
    }

    public static void exitUploadImageThread()
    {
        working = false;
        try
        {
            interrupted();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }


}
